//package  com.txts.admin.beidou.api.v1.controller;
//
//import  com.txts.admin.beidou.api.v1.dto.MessageReceiveRequest;
//import  com.txts.admin.beidou.api.v1.dto.MessageReceiveResponse;
//import  com.txts.admin.beidou.api.v1.util.beidouMessageParser;
//import  com.txts.admin.beidou.api.v1.util.beidouMessageParser.ParsedMessage;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestHeader;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import jakarta.validation.Valid;
//import java.util.UUID;
//
//@RestController
//@RequestMapping("/api/message")
//public class MessageController {
//
//    @PostMapping(value = "/receive", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
//    public ResponseEntity<MessageReceiveResponse> receive(
//            @RequestHeader(HttpHeaders.CONTENT_TYPE) String contentType,
//            @RequestHeader(value = "RequestId", required = false) String requestId,
//            @Valid @RequestBody MessageReceiveRequest request) {
//
//        if (requestId == null || requestId.isEmpty()) {
//            requestId = UUID.randomUUID().toString();
//        }
//
//        // 打印原始 Content
//        String hex = request.getContent();
//        System.out.println("Received Content: " + hex);
//
//        // 解析 Content
//        try {
//            ParsedMessage parsed = beidouMessageParser.parseContent(hex);
//            System.out.println("Parsed Message: \n" + parsed);
//        } catch (Exception e) {
//            System.err.println("Failed to parse Content: " + e.getMessage());
//        }
//
//        // TODO: 根据业务需求处理 parsed 数据或原始 request
//
//        MessageReceiveResponse response = new MessageReceiveResponse();
//        response.setRequestId(requestId);
//        response.setCode("ok");
//        return ResponseEntity.ok()
//                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
//                .body(response);
//    }
//}


package com.txts.road.admin.beidou.api.v1.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.txts.road.admin.beidou.api.v1.model.MessageEntity;
import com.txts.road.admin.beidou.api.v1.model.MessageReceiveRequest;
import com.txts.road.admin.beidou.api.v1.model.MessageReceiveResponse;
import com.txts.road.admin.beidou.api.v1.model.vo.MessageVO;
import com.txts.road.admin.beidou.api.v1.service.BeidouMessageService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

@RestController
@RequestMapping("/api/message")
@Tag(name = "北斗信息接口")
public class BeidouMessageController {

    @Resource(name = "beidouMessageService")
    private BeidouMessageService messageService;


    @PostMapping("/receive")
    public ResponseEntity<MessageReceiveResponse> receive(
            @RequestHeader(value = "RequestId", required = false) String requestId,
            @Valid @RequestBody MessageReceiveRequest request) {

        if (requestId == null || requestId.isEmpty()) {
            requestId = UUID.randomUUID().toString();
        }
        return ResponseEntity.ok(messageService.receive(requestId, request));
    }

    @GetMapping("/messages/latest-by-id")
    public ResponseEntity<MessageVO> getLatestMessageByIdNumber(@RequestParam String idNumber) {
        try {
            return ResponseEntity.ok(messageService.getLatestMessageByIdNumber(idNumber));
        } catch (EmptyResultDataAccessException e) {
            // 如果没有找到，返回 404 或者一个空对象
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }

    @GetMapping("/fence/geojson")
    public ResponseEntity<Map<String, Object>> getFenceGeoJson() {
        return ResponseEntity.ok(messageService.getFenceGeoJson());
    }

    @GetMapping("/messages/by-time")
    public ResponseEntity<?> getMessagesByTimeRange(
            @RequestParam String idNumber,
            @RequestParam String startTime,
            @RequestParam String endTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start, end;

        try {
            start = LocalDateTime.parse(startTime, formatter);
            end = LocalDateTime.parse(endTime, formatter);
        } catch (DateTimeParseException e) {
            return ResponseEntity.badRequest().body("时间格式错误，应为 yyyy-MM-dd HH:mm:ss");
        }

        if (Duration.between(start, end).toDays() > 31) {
            return ResponseEntity.badRequest().body("只能查询一个月以内的数据");
        }
        return ResponseEntity.ok(messageService.getMessagesByTimeRange(idNumber, start, end));

    }


}

